/* 文章分类服务
 * @Author: Leil 
 * @Date: 2018-08-23 11:05:16 
 * @Last Modified by: Leil
 * @Last Modified time: 2018-09-05 16:01:34
 */
const categoryModel = require('../models/category')
const postService = require('./postService')

// 添加一个类别
async function addOneCategory(data) {
    let result = {}
    let res = await categoryModel.addOneCategory(data).catch(error => {
        console.log(error.errmsg)
        result.error = error.errmsg
        result.info = '添加类别失败'
    })
    if (res) {
        // let categories = await categoryModel.getCategories().catch(error => {
        //     console.log(error.errmsg)
        //     result.info = '添加类别成功，查询失败'
        //     result.error = error.errmsg
        // })
        result.success = 'success'
        result.info = '添加成功!'
        // result.categories = categories
        // console.log(categories)
    }
    // console.log(result)
    return result
}

// 获取所有的类别
async function getAllCategories() {
    let data = {}
    await categoryModel.getCategories()
        .then(categories => {
            // console.log(categories)
            data = categories
        })
        .catch(error => {
            console.log(error.errmsg)
        })

    let arr = []
    for (let key in data) {
        arr.push(postService.getPostsCountByCategoryId(data[key]._id.toString()))
    }
    await Promise.all(arr)
        .then(results => {
            for (let key in results) {
                data[key].count = results[key]
            }
        })
    // console.log(data)
    return data
}

// 根据id删除文章类别
async function delCategoryById(categoryId) {
    let result = {}
    let res = await categoryModel.delCategoryById(categoryId).catch(error => {
        console.log(error.errmsg)
        result.error = error.errmsg
        result.info = '删除失败!'
    })
    if (res) {
        result.info = '删除成功!'
    }
    return result;
}

// 根据id获取文章类别
async function getCategoryById(categoryId) {
    let category = await categoryModel.getCategoryById(categoryId).catch(error => {
        console.log(error.errmsg)
    })
    return category
}

// 根据id更新文章类别
async function updateCategoryById(categoryId, data) {
    let result = {}
    let res = await categoryModel.updateCategoryById(categoryId, data).catch(error => {
        console.log(error.errmsg)
        result.error = error.errmsg
        result.info = '更新失败!'
    })
    if (res) {
        result.info = '更新成功!'
    }
    return result
}

module.exports = {
    addOneCategory,
    getAllCategories,
    delCategoryById,
    getCategoryById,
    updateCategoryById
}